//
//  MSStarControl.m
//  testMasory
//
//  Created by xiangbo on 2018/9/21.
//  Copyright © 2018年 xiangbo. All rights reserved.
//

#import "MSStarControl.h"

@interface MSStarControl ()

// 前景视图
@property (nonatomic, strong) UIView *foregroundStarView;
// 背景视图
@property (nonatomic, strong) UIView *backgroundStarView;
// 星星个数
@property (nonatomic, assign) NSInteger numberOfStars;

//显示图片
@property (nonatomic, strong) UIColor *foreColor;

//背景图片
@property (nonatomic, strong) UIColor *backColor;

//显示图片
@property (nonatomic, strong) NSString *baseImageName;

//显示图片
@property (nonatomic, strong) UIImage *baseImage;

@end

@implementation MSStarControl

- (instancetype)initWithFrame:(CGRect)frame {
    // 初始化，这里我设置星星个数为5
    self = [super initWithFrame:frame];
    if (self) {
        _numberOfStars = 5;
        [self createDataAndUI];
    }
    return self;
}

// 考虑到使用xib的情况
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        _numberOfStars = 5;
        [self createDataAndUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame numberOfStars:(NSInteger)numberOfStars foreColor:(UIColor *)foreColor backColor:(UIColor *)backColor{
    return [self initWithFrame:frame numberOfStars:numberOfStars image:@"star_gray" foreColor:foreColor backColor:backColor];
}


-(instancetype)initWithFrame:(CGRect)frame numberOfStars:(NSInteger)numberOfStars image:(NSString *)imageName foreColor:(UIColor *)foreColor backColor:(UIColor *)backColor{
    if (self = [super initWithFrame:frame]) {
        _numberOfStars = numberOfStars;
        if (imageName) {
            _baseImageName = imageName;
        }
        [self createDataAndUI];
    }
    return self;
}
#pragma mark - Private Methods
// 创建视图
- (void)createDataAndUI {
    _scorePercent = 1;//默认为1
    _hasAnimation = NO;//默认为NO
    _allowIncompleteStar = NO;//默认为NO
    
    self.foregroundStarView = [self createStarViewWithImage:[self.baseImage imageByTintColor:self.foreColor]];
    self.backgroundStarView = [self createStarViewWithImage:[self.baseImage imageByTintColor:self.backColor]];
    
    [self addSubview:self.backgroundStarView];
    [self addSubview:self.foregroundStarView];
}

#pragma mark -Property
- (UIImage *)baseImage{
    if (!_baseImage) {
        _baseImage = [UIImage imageNamed:self.baseImageName];
    }
    return _baseImage;
}

- (UIColor *)foreColor{
    return [UIColor colorWithRed:255/255.f green:199/255.f blue:0/255.f alpha:1];
}

- (UIColor *)backColor{
    return [UIColor colorWithRed:218/255.f green:217/255.f blue:226/255.f alpha:1];
}

- (NSString *)baseImageName{
    if (!_baseImageName) {
        _baseImageName = @"star_gray";
    }
    return _baseImageName;
}

- (void)setAllowScore:(BOOL)allowScore{
    if (_allowScore == allowScore) {
        return;
    }
    _allowScore = allowScore;
    self.userInteractionEnabled = allowScore;
    if (allowScore) {
        // 添加点按手势（也可以添加拖动手势）
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTapRateView:)];
        tapGesture.numberOfTapsRequired = 1;
        [self addGestureRecognizer:tapGesture];
    }else{
        for (UIGestureRecognizer *gesture in self.gestureRecognizers) {
            [self removeGestureRecognizer:gesture];
        }
    }
}

#pragma mark -Method
- (void)userTapRateView:(UITapGestureRecognizer *)gesture {
    CGPoint tapPoint = [gesture locationInView:self]; // 手指当前点
    CGFloat offset = tapPoint.x;
    // 当前偏移的X值 = 手指当前的位置*（星星视图总宽度/星星个数）
    CGFloat realStarScore = offset / (self.bounds.size.width / self.numberOfStars);
    // ceilf函数：返回浮点数整数部分（舍弃小数点部分，往个位数进1）如12.234 → ceilf(12.234)=13
    // 这句的意思是 是否显示整星
    CGFloat starScore = self.allowIncompleteStar ? realStarScore : ceilf(realStarScore);
    // 用手指移动的距离/星星的个数  == 点亮星星个数
    self.scorePercent = starScore;
    // 代理方法，当星星百分比发生变化时候调用
    if ([self.delegate respondsToSelector:@selector(starControl:scorePercentDidChange:)]) {
        [self.delegate starControl:self scorePercentDidChange:self.scorePercent];
    }
}

- (UIView *)createStarViewWithImage:(UIImage*)image{
    UIView *view = [[UIView alloc] initWithFrame:self.bounds];
    view.clipsToBounds = YES;
    view.backgroundColor = [UIColor clearColor];
    for (NSInteger i = 0; i < self.numberOfStars; i ++){
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        imageView.userInteractionEnabled = YES;
        imageView.frame = CGRectMake(i * self.bounds.size.width / self.numberOfStars, 0, self.bounds.size.width / self.numberOfStars, self.bounds.size.height);
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [view addSubview:imageView];
    }
    return view;
}

#pragma mark - Get and Set Methods

- (void)setScorePercent:(CGFloat)scorePercent {
    scorePercent = scorePercent / self.numberOfStars;
    if (_scorePercent == scorePercent) {
        return;
    }
    // 得分范围我设置的是0~1 这个可以你自己设定
    if (scorePercent < 0) {
        _scorePercent = 0;
    } else if (scorePercent > 1) {
        _scorePercent = 1;
    } else {
        _scorePercent = scorePercent;
    }
    // 重新布局, 刷新视图
    __weak MSStarControl *weakSelf = self;
    CGFloat animationTimeInterval = self.hasAnimation ? 0.2 : 0;
    [UIView animateWithDuration:animationTimeInterval animations:^{
        weakSelf.foregroundStarView.frame = CGRectMake(0, 0, weakSelf.bounds.size.width * weakSelf.scorePercent, weakSelf.bounds.size.height);
    }];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
